<template>
	<view class="content">
		<view class="app-title ac">
			<view class="fl" @click="back">
				<image class="back" src="/static/img/back.png"></image>
			</view>
			<view class="title">数据下载</view>
		</view>
		<view class="content-download">
			<view class="content-title">请选择需要下载的表数据</view>
			<view class="content-search">
				<u-cell-item title="开始时间:" :value="searchForm.startTime || '请选择'" @click="
				    show_date = true;
				    date_type = 'startTime';
				  ">
				</u-cell-item>
				<u-cell-item title="结束时间:" :value="searchForm.endime || '请选择'" @click="
				    show_date = true;
				    date_type = 'endime';
				  ">
				</u-cell-item>
			</view>
			<view class="check-btn">
				<u-button :custom-style="customStyle" type="primary" size="medium" @click="handleCheck(1)">
					全选
				</u-button>
				<u-button :custom-style="customStyle" type="primary" size="medium" @click="handleCheck(2)">
					反选
				</u-button>
			</view>
			<view class="content-list">
				<view v-for="(item, index) in dataList" :key="index">
					<u-checkbox v-model="item.checked" v-if="item.name" :name="item.name"
						@change="(val) => checkChange(val, item)">{{item.name}}</u-checkbox>
				</view>
			</view>
			<view class="download-btn">
				<u-button :custom-style="customStyle" type="primary" size="medium" @click="handleDownload">
					下载
				</u-button>
				<u-button :custom-style="customStyle" type="primary" size="medium" @click="handleCancel">
					取消
				</u-button>
			</view>
		</view>
		<u-picker v-model="show_date" mode="time" :params="timeParams" @confirm="setDate" @cancel="onCancel"></u-picker>
		<web-view v-if="webSrc" :src="webSrc" :webview-styles="webviewStyles" @message="postMessage"></web-view>
	</view>
</template>
<script>
	import dayjs from "../../static/plugins/js/dayjs/dayjs.min.js";
	import {
		SYS_APP_CONTROLLER
	} from "../../api/sys";

	var wv; // 计划创建的webview
	var currentWebview;
	const info = uni.getSystemInfoSync();
	export default {
		data() {
			return {
				searchForm: {
					startTime: "",
					endTime: "",
				},
				show_date: false,
				timeParams: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true,
				},
				customStyle: {
					// backgroundColor: "#15c6ac",
					width: "20%",
				},
				dataList: [],
				webviewStyles: {
					// width: 0
					top: "10000"
				},
				webSrc: ""
			};
		},
		onReady() {


			setTimeout(() => {
				// 获取当前页面的webview对象
				// this.getWebView(currentWebview); // 如果是页面初始化调用时，需要延时一下
			}, 1500);
		},
		onLoad() {
			// // #ifdef APP-PLUS
			// plus.screen.lockOrientation("portrait-primary");
			// // #endif
		},
		mounted() {
			this.$nextTick(() => {
				this.getData();
			})
		},
		methods: {
			getWebView() {
				currentWebview = this.$scope.$getAppWebview();
				setTimeout(function() {
					wv = currentWebview.children()[0];
					wv && wv.setStyle({
						scalable: true,
						top: "1000",
						height: 0,
						width: 0,
					});
				}, 500);
				// #ifdef APP-PLUS
				// #endif
			},
			postMessage(data) {   
				console.log(data);
				this.webSrc = "";
			},
			handleDownload() {
				let list = this.dataList.filter((item) => item.checked);
				this.webSrc = "/hybrid/html/download.html";
				this.getWebView();
				setTimeout(function() {
					wv.evalJS(`download(${JSON.stringify(list)})`);
				}, 1000);
				console.log(list, 111);

				return;
				uni.showLoading({
					title: "下载中"
				});
				list.forEach((item) => {
					let params = {
						tableNameC: item.tableNameC || "",
						tableNameE: item.tableNameE || "",
						stratTimeName: item.stratTimeName || "",
						endTimeName: item.endTimeName || "",
						startTime: this.searchForm.startTime,
						endTime: this.searchForm.endTime,
					}
					// 	this.fetch(
					// 		"post",
					// 		this.$store.state.baseUrl + SYS_APP_CONTROLLER.APP_DOWNLOAD_SQL,
					// 		params,
					// 		false,
					// 		false,
					// 		false,
					// 		'arraybuffer'
					// 	).then((res) => {
					// 		const contentDisposition = res && res.header && res.header["content-disposition"] || res.header["Content-Disposition"] || "";
					// 		if (contentDisposition) {
					// 			let arr = contentDisposition.split(";")
					// 			let nameArr = arr.length && arr[2].split("=");
					// 			let name = nameArr[1] && decodeURIComponent(nameArr[1]);
					// 			name = name.replace(/^"|"$/g, '');
					// 			this.saveFile(name, res.data);
					// 		} else {
					// 			uni.showToast({
					// 				title: "缺少contentDisposition",
					// 				icon: "none",
					// 			});
					// 		}
					// 	}).catch((err) => {
					// 		console.log(err);
					// 		this.fail();
					// 	}).finally(() => {
					// 		uni.hideLoading();
					// 	})
				})
			},
			saveFile(fileName, fileInfo, callback) {
				// 请求本地文件系统对象
				let path = "data/" + fileName;
				plus.io.requestFileSystem(
					plus.io.PUBLIC_DOWNLOADS, // 文件系统中的根目录
					(entry) => {
						// 文件在手机中的路径
						try {
							entry.root.getFile(
								path, {
									create: true
								},
								(fileEntry) => {
									fileEntry.createWriter((writer) => {
										// 写入文件成功完成的回调函数
										writer.onwrite = (e) => {
											this.success();
										};
										// 写入数据
										writer.writeAsBinary(fileInfo);
										// writer.write(fileInfo);
									});
								},
								(e) => {
									console.log(e);
									this.fail();
								}
							);
						} catch (error) {
							console.log(error);
							this.fail();
						}
					},
					(e) => {
						console.log(e);
						this.fail();
					}
				);
			},
			success() {
				uni.showToast({
					title: "下载成功",
					icon: "none",
				});
			},
			fail() {
				uni.showToast({
					title: "下载失败",
					icon: "none",
				});
			},
			getData() {
				this.dataList = [];
				// this.dataList = [
				// 	{
				// 		tableNameC: "用户表",
				// 		tableNameE: "111",
				// 		stratTimeName: "111",
				// 		endTimeName: "111",
				// 	},
				// 	{
				// 		tableNameC: "用户表2",
				// 		tableNameE: "111",
				// 		stratTimeName: "111",
				// 		endTimeName: "111",
				// 	},
				// 	{
				// 		tableNameC: "用户表3",
				// 		tableNameE: "111",
				// 		stratTimeName: "111",
				// 		endTimeName: "111",
				// 	}
				// ]
				this.dataList = this.dataList.map((item) => {
					return {
						...item,
						name: item.tableNameC,
					}
				});
				this.fetch(
					"post",
					this.$store.state.baseUrl + SYS_APP_CONTROLLER.APP_QUERY_SQL_TABLE
				).then((res) => {
					if (res.returnCode == 2004) {
						this.dataList = res.data?.map((item, index) => {
							return {
								...item,
								index: index,
								name: item.tableNameC,
								checked: false,
							}
						});
					}
				})
			},
			handleCheck(type) {
				if (type == 1) {
					this.dataList.map(item => {
						item.checked = true;
					})
				} else if (type == 2) {
					this.dataList.map(item => {
						item.checked = !item.checked;
					})
				}
			},
			checkChange(val, item) {
				// this.dataList.map((it, index) => {
				// 	if (item.index == index) it.checked = val.value;
				// })
				this.dataList[item.index].checked = val.value;
			},
			handleCancel() {
				// this.searchForm = {
				//   startTime: "",
				//   endTime: "",
				// }
			},
			setDate(obj) {
				let str = `${obj.year}-${obj.month}-${obj.day} ${obj.hour}:${obj.minute}:${obj.second}`;
				this.searchForm[this.date_type] = str;
				this.onCancel();
			},
			onCancel() {
				this.show_date = false;
			},
			back() {
				uni.navigateTo({
					url: "/pages/index/index",
				});
			},
		},
		destroyed() {},
	};
</script>
<style scoped lang="less">
	.content {
		height: 100vh;
		position: fixed;
		width: 100%;
		background: #fff;

		.ac {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
		}

		.app-title {
			.icon-select {
				width: 15px;
				height: 15px;
				margin-left: 5px;
				vertical-align: middle;
			}

			.title {
				width: 100%;
			}
		}

		.content-download {
			padding: 0 10px;

			.content-title {
				margin-top: 10px;
				font-size: 16px;
			}

			.content-search {}

			.check-btn {
				margin-top: 10px;

				uni-button {
					margin-right: 10px;
				}
			}

			.content-list {
				margin-top: 20px;

				.u-checkbox {
					display: flex;
					margin-bottom: 5px;
				}
			}

			.download-btn {
				position: fixed;
				width: 100%;
				bottom: 5%;
				display: flex;
				justify-content: center;

				uni-button {
					margin-right: 10px;
				}
			}
		}
	}
</style>